<?php
/**
 * Created by PhpStorm.
 * User: Lee
 * Date: 2020/1/3
 * Time: 9:51
 */
namespace App\Services\System;

use App\Common\Exception\ErrorException;
use App\Http\Controllers\Excel\ExcelExport;
use App\Http\Controllers\Excel\ExcelImport;
use App\Repositories\System\UserRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\System\User;
use App\Models\System\Menu;
use App\Models\System\RoleUser;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\System\Menu2;


/**
 * 系统管理-用户管理 (服务)
 */
class UserService
{
    /** @var UserRepository $userRepository */
    private $userRepository;

    public function __construct()
    {
        $this->userRepository = app('userRepository');
    }

    // 获取列表
    public function getList($requestData)
    {
        //1.用户表先筛选10条记录
        $where = [];
        if(isset($requestData['filters']['name']) && !empty($requestData['filters']['name'])){
            $where[] = ['users.nickname','like','%'.$requestData['filters']['name'].'%'];
        }
        $role_id = 0;
        if(isset($requestData['filters']['role']) && !empty($requestData['filters']['role'])){
            $role_id = $requestData['filters']['role'];
        }
        if(isset($requestData['filters']['username']) && !empty($requestData['filters']['username'])){

            $where[] = ['users.user_id','like','%'.$requestData['filters']['username'].'%'];
        }
        if(isset($requestData['filters']['status']) && !empty($requestData['filters']['status'])){
            if ($requestData['filters']['status'] == '2'){
                $where[] = ['users.active_flag','=',0];
            }else{
                $where[] = ['users.active_flag','=',1];
            }
        }
        if(isset($requestData['filters']['group_id']) && !empty($requestData['filters']['group_id'])){
            //$qrySql .= " AND t.group_id=".$requestData['filters']['group_id']."";
        }

        $where[] = ['users.deleted','=',0];
        $where[] = ['users.disabled','=',0];
        $where[] = ['users.username','like','%\_%'];

        $result = User::where($where)
                ->select('users.*')
                ->with('roles')
                ->when($role_id,function($q,$role_id){
                    $q->leftJoin('role_user','users.id','=','role_user.user_id')->where('role_user.role_id',$role_id);
                })
                ->paginate(10,['*'],'page',$requestData['page'])->toArray();

        $row = ['total' => $result['total'],'data' => []];


        foreach($result['data'] as $k=>$v){
            $row['data'][] = [
                'id' => $v['id'],
                'user_id' => $v['user_id'],
                'user_name' => $v['nickname'],
                // 'active_flag' => $v['active_flag'],
                'rolename' => implode(',',array_column($v['roles'],'rolename')),
                'roleid' => implode(',',array_column($v['roles'],'id')),
            ];
        }

        //dd($row);
        return $row;
    }

    //获取所有角色
    public function getAllRole()
    {
        $filters = [];

        /** @var \App\Services\System\RoleService $roleService */
        $roleService = app('roleService');
        $filters[] = ['id','!=',SYSTEM_ROLE];

        $result = $roleService->getAll($filters,['level'=>'asc'],['id','rolename']);

        return $result->toArray();
    }

    //设置用户角色
    public function setUserRole($requestData)
    {
        $id = $requestData['id'];
        /** @var \App\Models\System\User $user */
        $user = $this->userRepository->get($id);
        if(!$user){
            throw new ErrorException('用户不存在');
        }
        //$user->roles()->detach();
        RoleUser::where('user_id',$id)->where('role_id','!=',SYSTEM_ROLE)->delete();
        User::where('id',$id)->update(['curr_role_id'=>0]);
        if (is_array($requestData['roleid'])){
            foreach ($requestData['roleid'] as $roleid){
                $user->roles()->attach($roleid);
            }
        }else{
            $user->roles()->attach($requestData['roleid']);
        }

    }

    public function setUserStatus($requestData)
    {
        $id = $requestData['id'];
        $status = '1';
        if($requestData['status'] == '2'){
            $status = '0';
        }
        if (is_array($id)){
            foreach ($id as $v) {
                $this->userRepository->edit(['active_flag' => $status],$v);
            }
        }else{
            $this->userRepository->edit(['active_flag' => $status],$id);
        }


    }

    //判断用户角色
    public function getUserRole($requestData)
    {
        $id = $requestData['id'];
        /** @var \App\Models\System\User $user */
        $user = $this->userRepository->get($id);
        if(!$user){
            throw new ErrorException('用户不存在');
        }
        $role = $user->roles()->get()->first();
        if (!$role){
            return TEACHER_ROLEID;
        }else{
            return $role->id;
        }

    }

    public function getGroupTree()
    {
        /** @var \App\Services\System\GroupService $groupService */
        $groupService = app('groupService');

        $menus = [];
        $school = Auth::user()->school();
        $schoolObject = [
            'id' => $school['id'],
            'title' => $school['group_name'],
            'group_flag' => $school['group_flag'],
            'spread' => true,
            'children' => array(),
        ];
        $menus[$school['id']] = $schoolObject;

        $grades = $groupService->getAllGradeCore($school['id']);
        $grades = $grades->toArray();
        foreach ($grades as $grade){
            $gradeObject = [
                'id' => $grade['id'],
                'title' => $grade['group_name'],
                'group_flag' => $grade['group_flag'],
                'spread' => false,
                'children' => array(),
            ];
            $menus[$school['id']]['children'][$grade['id']] = $gradeObject;

            $classes = $groupService->getAllClassCore($grade['id']);
            $classes = $classes->toArray();
            foreach ($classes as $class){
                $classObject = [
                    'id' => $class['id'],
                    'title' => $class['group_name'],
                    'group_flag' => $class['group_flag']
                ];
                $menus[$school['id']]['children'][$grade['id']]['children'][$class['id']] = $classObject;
            }
        }

        $menus = array_values($menus);
        foreach($menus as $k => $v){
            $menus[$k]['children'] = array_values($menus[$k]['children']);

            foreach($menus[$k]['children'] as $k_g => $v_g){
                $menus[$k]['children'][$k_g]['children'] =  array_values( $menus[$k]['children'][$k_g]['children']);
            }
        }

        return $menus;
    }

    /**
     * 获取菜单
     * @author lxy
     * @datetime 2020-11-16
     */
    public function getUserMenus($request)
    {

        $user = auth()->user();
        $role_id = $user->cur_role_id;

        // $roles = $user->roles()->get()->toArray();
        // if(!$roles){
        //     return [];
        // }

        // if(!empty($request['role_id'])){
        //     $roleids = $request['role_id'];
        // }else{
        //     $roles = $roles;
        //     $role_id = [];
        //     foreach ($roles as $role){
        //         $role_id[] = $role['id'];
        //     }
        //     if(!$role_id){
        //         return [];
        //     }
        //     $roleids = $role_id[0];
        // }

        $menuids = DB::table('rolepowers')->where('role_id',$role_id)->get()->pluck('actionid')->toArray();

        if(!$menuids){
            return [];
        }

        $menus = Menu2::select('menus.id','menus.pid','menus.name as title','menus.icon','menus.path as href','menus.is_ml as type','menus.openType')
            ->where('pid',0)
            ->where('type',1)
            ->where('status',1)
            ->whereIn('id',$menuids)
            ->with('children')
            ->orderBy('menus.sort')
            ->get()->toArray();

        return $menus;
    }

    /**
     * @Description: 设置用户当前角色
     * @Author: kzj
     * @datetime: 2022-12-01
     */
    public function setUserCurRole($request)
    {
        $user = Auth::user();
        $roles = $user->roles()->pluck('roles.id');

        $role_ids = $roles->toArray();
        if (!in_array($request['role_id'], $role_ids)){
            throw new ErrorException('用户不存在对应角色');
        }

        $result = User::where('id', $user->id)->update(['curr_role_id' => $request['role_id']]);

        return $result;
    }


    public function updateInfo($request)
    {
        ini_set('memory_limit', '512M');
        $data = Excel::toArray(new ExcelImport(), request()->file('file'));

        $data = $data[0];
        if (count($data) < 2) {
            throw new \Exception('模板不能为空');
        }

        $errCount = 0;
        foreach ($data as $k => &$v) {
            if ($k > 0) {
                if(!$v[0] || !$v[1]) {
                    array_push($v, '该行数据都不能为空！');
                    $errCount++;
                    continue;
                }

                $updateRes = User::where('user_id', trim($v[0]))->update(['id_card' => $v[1]]);
                if(!$updateRes) {
                    array_push($v, '更新失败，请核对该用户的账号和身份证号是否匹配正确！');
                }
            } else {
                if(
                    !(isset($v[0]) && trim($v[0]) == '账号') ||
                    !(isset($v[1]) && trim($v[1]) == '身份证号')
                ) {
                    throw new \Exception('模板错误，请上传正确的模板！第一行为“账号”，“身份证号”作为列表头。');
                }

                array_push($v, '错误提示');
            }
        }

        $result = [
            'is_fail' => 1, //1-成功 0-失败
            'msg' => '导入成功',
            'file_name' => ''
        ];
        if ($errCount == 0) {
            return $result;
        } else {
            //保存错误文件
            $file_name = md5(auth()->user()->id . time()) . '.xlsx';
            Excel::store(new ExcelExport(array_values($data)), $file_name, 'excel');

            $result['is_fail'] = 0;
            $result['msg'] = '导入失败';
            $result['file_name'] = '/download/excel/' . $file_name;
            return $result;
        }
    }


    //*******************外部调用方法****************************************************
    public function getCore($id,$keyName='id',$columns=['*']){
        return $this->userRepository->get($id, $keyName,$columns);
    }

    public function delCore($id,$keyName=false){
        $row = $this->userRepository->get($id, $keyName);
        if ($row){
            return $this->userRepository->delete($id, $keyName);
        }else{
            return true;
        }

    }

}
